package com.mc.mcgoweb.utils.xml2bean;

import com.alibaba.fastjson.JSON;
import com.mc.mcgoweb.utils.HttpUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.Map;
import java.util.TreeMap;

public class WmsLink {

    private static final Logger logger = LoggerFactory.getLogger(WmsLink.class);


    public static String sendToWms(String method, String body) throws Exception {


        Map<String, String> parms = new TreeMap<>();

        parms.put("method", method);
        parms.put("timestamp", "2019-04-22 04:22:22");
        parms.put("format", "xml");
        parms.put("app_key", WmsConstant.APPKEY);
        parms.put("v", "2.0");
        parms.put("customerId", WmsConstant.CUSTOMID);
        parms.put("sign_method", "md5");


        String digestStr = WmsConstant.APPSECRET;

        for (Map.Entry<String, String> item : parms.entrySet()) {
            digestStr += item.getKey() + item.getValue();
        }
        digestStr += body;
        digestStr += WmsConstant.APPSECRET;


        String digest = DigestUtils.md5Hex(digestStr).toUpperCase();


        String urlParams = "?sign=" + digest;
        for (Map.Entry<String, String> item : parms.entrySet()) {
            String value = URLEncoder.encode(item.getValue(), "UTF-8");
            urlParams += "&" + item.getKey() + "=" + value;
        }

        String result = HttpUtils.sendPost(WmsConstant.URL + urlParams, body);
        return result;

    }

    public static String bulidResult(boolean success, String msg) {

        StringBuilder sb = new StringBuilder();
        if (success) {
            sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            sb.append("<response>");
            sb.append("<flag>success</flag>");
            sb.append("<code></code>");
            sb.append("<message></message>");
            sb.append("</response>");
        } else {
            sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            sb.append("<response>");
            sb.append("<flag>failure</flag>");
            sb.append("<code></code>");
            sb.append("<message>" + msg + "</message>");
            sb.append("</response>");
        }
        return sb.toString();
    }


    public static boolean isWmsSign(HttpServletRequest request, @RequestBody String body) {

        boolean result = false;

        Map<String, String> parms = new TreeMap<>();
        parms.put("method", "");
        parms.put("timestamp", "");
        parms.put("format", "");
        parms.put("app_key", "");
        parms.put("v", "2.0");
        parms.put("customerId", "");
        parms.put("sign_method", "");

        for (Map.Entry<String, String> item : parms.entrySet()) {

            if (StringUtils.isBlank(request.getParameter(item.getKey()))) {
                logger.info("{}参数为空", item.getKey());
                break;
            } else {
                parms.put(item.getKey(), request.getParameter(item.getKey()));
            }
        }

        logger.info("参数集合数据为:" + JSON.toJSONString(parms));

        String digestStr = WmsConstant.APPSECRET;

        for (Map.Entry<String, String> item : parms.entrySet()) {

            logger.info("组合摘要{}:{}", item.getKey(), item.getValue());
            digestStr += item.getKey() + item.getValue();
        }
        logger.info("请求参数digestStr:{}，body:{}", digestStr, body);
        digestStr += body;

        digestStr += WmsConstant.APPSECRET;

        logger.info("系统计算摘要值为：{}", digestStr);

        String digest = DigestUtils.md5Hex(digestStr).toUpperCase();
        logger.info("系统计算签名为：{}", digest);

        String requestDigest = request.getParameter("sign");
        logger.info("请求签名为：{}", requestDigest);

        result = digest.equals(requestDigest);
        return result;
    }

}
